// init
package database

import (
	"github.com/Unknwon/goconfig"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
	"martini_template/componnet"
)

var Engine *xorm.Engine
var dbConfig *goconfig.ConfigFile
var err error

func InitDb(env string) *xorm.Engine {
	loadConfigFile()
	driver, err := dbConfig.GetValue(env, "driver")
	host, _ := dbConfig.GetValue(env, "host")
	port, _ := dbConfig.GetValue(env, "port")
	user, _ := dbConfig.GetValue(env, "user")
	password, _ := dbConfig.GetValue(env, "password")
	database, _ := dbConfig.GetValue(env, "database")
	charset, _ := dbConfig.GetValue(env, "charset")
	Engine, err = xorm.NewEngine(driver, user+":"+password+"@tcp("+host+":"+port+")/"+database+"?charset="+charset)
	//defer Engine.Close()
	if err != nil {
		panic(err)
	}
	Engine.ShowSQL(true)
	Engine.SetLogger(xorm.NewSimpleLogger(componnet.SQLlogger))
	Engine.Logger().SetLevel(core.LOG_DEBUG)
	err = Engine.Ping()
	if err != nil {
		panic(err)
	} else {
		prefix, _ := dbConfig.GetValue(env, "table_prefix")
		tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, prefix)
		Engine.SetTableMapper(tbMapper)
		return Engine
	}
}

//加载配置
func loadConfigFile() {
	dbConfig = componnet.DbConfig
}
